import { ArgumentMetadata, Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import { plainToClass } from "class-transformer"
import { validate } from "class-validator"
@Injectable()
export class ValidationPipe implements PipeTransform {
 async transform(value: any, metadata: ArgumentMetadata) {
    const { metatype } = metadata
    // 如果没有传入验证规则，不验证，直接返回
    if (!metatype || this.toValidate(metatype)) {
      return value;
    }
    // 将对象转换成class来验证
    const object = plainToClass(metatype,value)
    const errors = await validate(object)
    if (errors.length>0) {
     // 只需要取第一个错误信息并返回即可
      const msg = Object.values(errors[0].constraints)[0]
      throw new BadRequestException(`Validation failed: ${msg}`)
    }
    return value
  }

  private toValidate(metatype: any): boolean {
    const types: any[] = [String, Array, Object, Number, Boolean]
    return !types.includes(metatype)
  }
}
